package com.leyou.search.listener;

import com.leyou.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

// 用来监听rabbitMQ的类，@Component定义注解注册到Spring容器
@Component
public class GoodsListener {

    // 封装查询创建es数据的service
    @Autowired
    private SearchService searchService;


    /**
     *  用于接收insert和update消息的MQ方法
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            // 队列名称leyou.create.index.queue
            value = @Queue(value = "leyou.create.index.queue", durable = "true"),
            exchange = @Exchange(
                    // 交换机名称leyou.item.exchange--发送消息就是发到这个交换机里了
                    value = "leyou.item.exchange",
                    // 忽略异常
                    ignoreDeclarationExceptions = "true",
                    // 使用topic方式
                    type = ExchangeTypes.TOPIC),
            // 接收的数据类型
            key = {"item.insert", "item.update"}))
    public void listenerCreate(Long id) throws IOException {
        if (id == null) {
            return;
        }
        // 确定收到消息后，创建或者更新索引库
        this.searchService.createIndex(id);
    }


    /**
     *  用于接收delete删除指令消息的MQ方法,根据spuID
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            // 队列名称leyou.create.index.queue
            value = @Queue(value = "leyou.create.index.queue", durable = "true"),
            exchange = @Exchange(
                    // 交换机名称leyou.item.exchange--发送消息就是发到这个交换机里了
                    value = "leyou.item.exchange",
                    // 忽略异常
                    ignoreDeclarationExceptions = "true",
                    // 使用topic方式
                    type = ExchangeTypes.TOPIC),
            // 接收的数据类型
            key = {"item.delete"}))
    public void listenerDelete(Long id) throws IOException {
        if (id == null) {
            return;
        }
        // 删除索引库
        this.searchService.deleteIndex(id);
    }
}
